package net.csdn.business.common.config.oss;

import com.aliyun.cdn20180510.Client;
import com.aliyun.teaopenapi.models.Config;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import net.csdn.business.common.config.oss.AliYunOssProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author zhangyl
 * date 2022-06-22 2:34 下午
 */
@Configuration
@EnableConfigurationProperties(AliYunOssProperties.class)
public class AliYunOssConfig {


    @Bean
    public IClientProfile clientProfile(AliYunOssProperties properties){
        DefaultProfile profile = DefaultProfile.getProfile(properties.getRegionId(), properties.getAccessKey(), properties.getSecretKey());
        return profile;
    }


    @Bean
    public AssumeRoleRequest assumeRoleRequest(AliYunOssProperties properties){
        //以下Policy用于限制仅允许使用临时访问凭证向目标存储空间bucket上传文件。
        String policy = "{\n" +
                "    \"Version\": \"1\", \n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Action\": [\n" +
                "                \"oss:PutObject\"\n" +
                "            ], \n" +
                "            \"Resource\": [\n" +
                "                \"acs:oss:*:*:"+properties.getBucketName()+"/*\"\n" +
                "            ], \n" +
                "            \"Effect\": \"Allow\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        AssumeRoleRequest request=new AssumeRoleRequest();
        request.setSysMethod(MethodType.POST);
        request.setRegionId(properties.getRegionId());
        request.setRoleArn(properties.getRoleArn());
        request.setPolicy(policy);
        request.setDurationSeconds(15*60L);
        request.setRoleSessionName(properties.getRoleSessionName());
        return request;
    }

    @Bean
    public IAcsClient defaultAcsClient(IClientProfile profile){
        IAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

    @Bean
    public Client cdnClient(AliYunOssProperties properties) throws Exception{
        Config config = new Config()
                // 您的 AccessKey ID
                .setAccessKeyId(properties.getAccessKey())
                // 您的 AccessKey Secret
                .setAccessKeySecret(properties.getSecretKey());
        // 访问的域名
        config.endpoint = properties.getCdnEndpoint();
        return new com.aliyun.cdn20180510.Client(config);

    }
}